package com.zxmzy.scaffold.http.cookie

import android.content.Context
import android.content.SharedPreferences
import com.franmontiel.persistentcookiejar.persistence.CookiePersistor
import com.franmontiel.persistentcookiejar.persistence.SerializableCookie
import com.zxmzy.scaffold.http.RequestManager
import okhttp3.Cookie

/**
 * @author zhangxiaoming
 * @date 2023/8/24
 * @description
 */
class CookiePersist : CookiePersistor {
    companion object {
        private const val NAME = "CookiePersistence"
    }

    override fun loadAll(): MutableList<Cookie> {
        val cookies = mutableListOf<Cookie>()
        for (entry in getSharedPreferences().all.entries) {
            val serializedCookie: String = entry.value.toString()
            val cookie: Cookie? = SerializableCookie().decode(serializedCookie)
            cookie?.let { cookies.add(it) }
        }
        return cookies
    }

    override fun saveAll(cookies: Collection<Cookie>?) {
        cookies ?: return
        val editor = getSharedPreferences().edit()
        for (cookie in cookies) {
            editor.putString(createCookieKey(cookie), SerializableCookie().encode(cookie))
        }
        editor.apply()
    }

    override fun removeAll(cookies: MutableCollection<Cookie>?) {
        cookies ?: return
        val editor = getSharedPreferences().edit()
        for (cookie in cookies) {
            editor.remove(createCookieKey(cookie))
        }
        editor.apply()
    }

    override fun clear() {
        getSharedPreferences().edit().clear().apply()
    }

    private fun createCookieKey(cookie: Cookie): String {
        return "${if (cookie.secure) "https" else "http"}://${cookie.domain}${cookie.path}|${cookie.name}"
    }

    private fun getSharedPreferences(): SharedPreferences {
        return RequestManager.get().appContext.getSharedPreferences(NAME, Context.MODE_PRIVATE);
    }
}